import requests
import re


def request_58_web(headers,page):
	# Get URL
	url = "http://cs.58.com/chuzu/pn" + page

	print("Getting the information, please wait minutes ....")

	res = requests.get(url,headers = headers)

	html = res.content.decode('utf-8')
	
	pat = '<li logr=.*?<img.*?lazy_src="(.*?)".*?<div class="des">.*?<a.*?>\n(.*?)</a>.*?<p class="room">(.*?) &nbsp;.*?<div class="money">.*?<b>(.*?)</b>.*?</li>'

	items = re.findall(pat,html,re.S)
	i = 1
	# Print information
	for item in items:
		print('Room ' + str(i) +':\n' +
		"标题:" + item[1].replace('\n','').strip() + '\n'
		"户型:" + item[2].replace('\n','').strip() + '\n'
		"价格:" + str(item[3]).replace('\n','').strip()  + '\n' + 
		"图片连接:" + item[0].replace('\n','').strip() + '\n' )
		i = i+1

	print("Total room on this page: " + str(len(items)))

if __name__ == '__main__':
	# Get headers
	headers = {
	'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
	'Accept-Language': 'zh-CN,zh;q=0.9',
	'Connection': 'keep-alive',
	'Host': 'cs.58.com',
	'Upgrade-Insecure-Requests': '1',
	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'
	}
	while True:
		page = input("Please input the page in 58 Page (0 to exit):\n")
		if page == '0':
			break
		elif re.match('^[0-9]+$',page):
			request_58_web(headers,page)
		else:
			print("You input wrong page!")
			break
